from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import get_object_or_404, render_to_response
from django.core.urlresolvers import reverse

class owner_required(object):
    """Checks to see whether the current user
    is the owner of the requested object
    """

    def __init__(self, id_keyword, object_model):
        self.id_keyword = id_keyword
        self.object_model = object_model

    def __call__(self, f):
        def newf(request, **kwargs):
            u = request.user
            if not u.is_authenticated():
                return HttpResponseRedirect(reverse('login'))
            object_id = kwargs[self.id_keyword]
            # retrieve object from database
            object = get_object_or_404(self.object_model, id=object_id)
            session_key = repr(object)
            # check session for ownership
            if request.session.get(session_key, False):
                kwargs['object'] = object
                return f(request, **kwargs)
            # check if current user is the owner
            elif object.is_owner(u): 
                request.session[session_key] = True
                kwargs['object'] = object
                return f(request, **kwargs)
            else:
                return render_to_response('denied.html',
                        context_instance=RequestContext(request))
        return newf
